using Microsoft.Samples.ServiceHosting.StorageClient;
using Log = Microsoft.Samples.ServiceHosting.HelloFabric.ApplicationEnvironment;

namespace KlearStorage
{
    public abstract class Setup
    {
        public abstract void CreateTables(StorageAccountInfo ai, string context);
        public abstract void FillTables(StorageAccountInfo ai, string context);


        public void DeleteAndCreateTables(StorageAccountInfo ai, string context)
        {
            var ts = TableStorage.Create(ai);
            Log.LogVerbose("Delete existing tables");
            bool deletedTables = false;
            try
            {
                var existingTables = ts.ListTables();
                foreach (var table in existingTables)
                {
                    deletedTables = true;
                    Log.LogInformation("Deleting table: " + table);
                    ts.DeleteTable(table);
                }
            }
            catch (System.Exception ex)
            {
                Log.LogError("ERROR: Could not access the tables! Check your settings and internet connection.\n\n" + ex);
                throw;
            }

            if (deletedTables)
            {
                Log.LogVerbose("Sleep for 1 minute; waiting for the tables to be deleted.");
                System.Threading.Thread.Sleep(60000);
            }

            Log.LogVerbose("Create tables");
            CreateTables(ai, context);

            var createdTables = ts.ListTables();
            foreach (var table in createdTables)
                Log.LogInformation("Created table: " + table);
        }
    }
}